<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Abiturient extends CI_Controller {

	public $data;
	function __construct()
	{
		parent::__construct();

		$data = new stdclass();

		header("Content-Type: text/html; charset=utf-8");
		$this->load->model('abiturient_model', 'abi');
		$this->load->model('user_model', 'user');
	}

	public function index()
	{
		$this->data->title = "Абитуриенты";

		if ($this->user->id())
		{
			$user = $this->user->getUser($this->user->id());

			switch ($user->tAccType) 
			{
				case 0:
					$pageData = $this->abi->getSendedVacancy($this->user->id());
					// if (!isset($this->test))
					// 	$this->load->model('test_model', 'test');
					// $res = $this->test->getById(3);
					// diepr($res);

					$this->data->addingJS[] = 'abiturientPage.js';
					$this->data->content = $this->load->view('indexPageAbiturient', array('sendedVacancy' => $pageData), true);
					break;

				case 1:
					$this->data->title = 'Абитуриенты-Коммисия';
					$this->data->content = $this->load->view('tableAbiturientsComission', array(
						'abiturients' => $this->abi->getTableCommission(),
						'disciplines' => $this->abi->getAllDisciplines()
						), true);
					break;

				case 2:
					$this->data->addingJS[] = 'abiturient.js';
					$this->data->addingJS[] = 'underscore-min.js';
					$this->data->title = 'Абитуриенты-Модератор';				
					$this->data->content = $this->load->view('tableAbiturients', array(
						'abiturients'	=> $this->abi->getAllAbiturient(),
						'disciplines'	=> $this->abi->getAllDisciplines(),
						'cities'		=> $this->user->getCities()
						), true);
					break;		
				
				default:
					die("я хз как ты сюда попал...");
					break;
			}
		}
		else
			$this->data->content = $this->load->view('unregistered', array(''), true);
			

		$this->load->view('index', $this->data);
	}

	public function add()
	{
		if ($this->user->id())
		{
			$this->data->addingJS[] = 'abiturient.js';
			
			$disciplines = $this->abi->getAllDisciplines();
			// diepr($disciplines);

			$this->data->title = "Добавить абитуриента";
			$this->data->content = $this->load->view('addDocument4Proff',array('disciplines' => $disciplines), true);
		}
		else
			redirect("/abiturient");

		$this->load->view('index', $this->data);
	}

	public function edit($id)
	{
		$data = new stdclass();
		$abiturient = new stdclass();

		$id = abs(@abs($id));
		$user = $this->user->getUser($this->user->id());

		if ($this->user->id() && ($user->tAccType == 1 || $user->tAccType == 2))
		{
			$abiturient = $this->abi->getAbiturById($id);

			$data->title = "Редактирование абитуриента";
			$data->content = $this->load->view('addAbitur', array('abiturient' => $abiturient), true);
		}
		else
			redirect("/abiturient");

		$this->load->view('index', $data);
	}

	public function save($update = false)
	{
		$data = new stdclass();
		$data =(object) $this->input->post();

		foreach ($data as $key => $value)	
			 $data->$key = htmlspecialchars($value);

		$user = $this->user->getUser($this->user->id());

		if ($this->user->id() && ($user->tAccType == 1 || $user->tAccType == 2))
		{
			$data->dCreate = now();

			if (!$update)
			{
				die(json_encode( $check = $this->abi->updaterDB('abiturient', $data) ) );
				$_SESSION['saveAbitur'] = 'Абитуриент успешно добавлен';
			}
			else
			{
				die(json_encode( $check = $this->abi->updaterDB('abiturient', $data, true) ) );
				$_SESSION['saveAbitur'] = 'Абитуриент успешно отредактирован';
			}
		}

	}

	public function confirm($value='')
	{
		# code...
	}

	public function delete($id=0)
	{
		$id = abs(@abs($id));

		$user = $this->user->getUser($this->user->id());

		if ($this->user->id() && ($user->tAccType == 1 || $user->tAccType == 2))
		{
			$del = $this->abi->delete($id);

			if($del)
				$_SESSION['saveAbitur'] = 'Абитуриент удален';
			else
			{
				$error = "Неизвестная ошибка при удалении";
				$_SESSION['error'] = $error;
			}
		}

		redirect('/abiturient/'); 
	}

	public function search($get = '')
	{
		$this->data->addingCSS[] = 'search.css';

		if ($query = $this->input->post('querySearch'))
		{
			$query = searchEncode($query);
			redirect('abiturient/search/'.$query);
		}

		// diepr($get);
		if (empty($get)) redirect('/abiturient');


		$get = urldecode(searchDecode($get));
		$_POST['querySearch'] = $get;
		$querySearch = clearSearchStr($get);
		$querySearch = getSearchElements($querySearch);

		if (!is_arr($querySearch))
		{
			$data->content = $this->load->view('404', array('text' => 'Запрос пустой или задан неверно.'), true);	
		}
		else
		{
			$querySearchAbiturients = $this->abi->getDataFromSearch($querySearch);
			$this->data->title = "Результаты поиска";
			$this->data->content = $this->load->view('searchResults', array('abiturients' => $querySearchAbiturients), true);
		}

		$this->load->view('index', $this->data);
	}

	public function getDiscInfo()
	{	
		$id = abs(intval($this->input->post('id')));
		$res = $this->abi->getDisciplines($id);

		echo json_encode(!empty($res)? $res : "ошибка запроса");
	}

	public function getAbiturientByFiltr()
	{
		$filtrs = $this->input->post();
		echo json_encode($this->abi->getAllAbiturient($filtrs));
	}

	function getAbiturientById()
	{
		$id = abs($this->input->post('id'));
		$res = $this->abi->getAbiturById($id);
		if ($res)
			die(json_encode($res));
		else 
			die(json_encode(array('err' => 1, 'text' => 'ошибка получения абитуриента')));
	}


//ДОБАВИТЬ В ЗАПИСЬ ПОЛЕЙ, КОТОРЫЕ НУЖНО ВЗЯТЬ С ЛИСТА САЛИХЪЯНЫЧА
	function checkAbiturForAdd()
	{
		$tDisc = abs(intval($this->input->post('tDisc')));
		$tUser =  $this->user->id();
		$res = $this->abi->checkUserAddenOnDisc($tDisc, $tUser);

		if ($res)
			die(json_encode(array('err' => 1, 'text' => 'Данная специальность уже в списке')));
		else
		{
			$user = $this->user->data();
			$user->tDiscipline = $tDisc;
			$user->dCreate = now();
			$user->tUser = $tUser;

			$check = $this->abi->updaterDB('abiturient', $user);

			// dieVD($check);
			if (!$check)
				die(json_encode(array('err' => 1, 'text' => 'Ошибка добавления абитуриента')));
			else
				die(json_encode(array('status' => "ok")));
		}

	}

	function deleteVacancy()
	{
		$id = abs(intval($this->input->post('id')));
		$check = $this->abi->checkUserAddenOnDisc('', $this->user->id(), $id);

		if ($check)
		{
			if ($this->abi->delete($id) === true)
				die(json_encode(array('status' => 'ok')));
			else
				die(json_encode(array('err' => 1, 'text' => 'Ошибка удаления абитуриента')));
		}
	}


	public function scores()
	{
		if ($this->user->id())
		{
			$this->data->title = 'Мои баллы';
			$this->data->content = $this->load->view('scores/list', array(), FALSE);;
		}
		else
		{
			$_SESSION['error'][] = 'Раздел "Мои баллы доступен только зарегистрированым"'; 
			redirect("/abiturient");
		}

		$this->load->view('index', $this->data);		
	}
}



/* Location: ./application/controllers/welcome.php */